package com.kuangstudy.controller.bloom;

import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.hash.Funnel;
import com.google.common.hash.Hashing;
import com.kuangstudy.entity.User;
import com.kuangstudy.service.bloom.BloomFilterHelper;
import com.kuangstudy.service.bloom.RedisService;
import io.rebloom.client.Client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class BloomController {

    @Autowired
    private Client rebloomClient;
    // 今日头条推荐数据
    final int size = 18;

    /**
     * 拉取18条推荐数据
     *
     * @param userid
     */
    @GetMapping("/rebloom")
    public List<Integer> rebloom(Integer userid) {
        String key = "redis:uid:filter:" + userid;
        List<Integer> list = new ArrayList<>();
        while (true) {
            // 步骤1：到大数据信息流服务，获取18条数据
            List<Integer> dataList = this.getArticleIds();
            // 步骤2：判断这18条数据，是否在布隆过滤器中，存在就进行过滤已读的数据
            String[] arrays = new String[dataList.size()];
            for (int i = 0; i < dataList.size(); i++) {
                arrays[i] = String.valueOf(dataList.get(i));
            }

            boolean[] booleans = this.rebloomClient.existsMulti(key, arrays);
            for (int i = 0; i < dataList.size(); i++) {
                boolean flag = booleans[i];
                if (!flag) {
                    list.add(dataList.get(i));
                } else {
                    log.info("过滤：{}", dataList.get(i));
                }
            }

            if (list.size() == size) {
                break;
            }
        }

        // 把本次读取出来的数据放入到布隆过滤器中，代表已读
        String[] strings = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strings[i] = String.valueOf(list.get(i));
        }
        this.rebloomClient.addMulti(key, strings);
        return list;
    }


    /**
     * 模拟信息流的大数据信息服务数据
     * 获取18条数据
     *
     * @return
     */
    private List<Integer> getArticleIds() {
        Random random = new Random();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            int id = random.nextInt(100000);
            list.add(id);
        }
        return list;
    }


    // 模拟某个用户，访问了1W篇文章，已读数据
    @GetMapping("/initusers")
    public void init(Integer userid) {
        String[] users = new String[10000];
        for (int i = 0; i < 10000; i++) {
            users[i] = String.valueOf(i);
        }
        this.rebloomClient.addMulti("redis:uid:filter:" + userid, users);
    }

}
